package top.appx.helper.email;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * Created by zwyhome on 2015/6/16.
 */
public class EmailHelper {

    public static String email_user;
    public static String email_password;
    static{
        Properties props = new Properties();
        try {
            props.load(EmailHelper.class.getResourceAsStream("/config.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        email_user = props.getProperty("email_user");
        email_password = props.getProperty("email_password");
    }

    public static void sendEmail(EmailModel model) throws Exception {
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.qq.com");
        props.put("mail.smtp.auth", "true"); // 允许smtp校验
        Session sendMailSession = Session.getInstance(props, null);
        try {
            Transport transport = sendMailSession.getTransport("smtp");
            // 连接你的QQ，注意用户名和密码必须填写正确，否则权限得不到
            transport.connect("smtp.qq.com", email_user, email_password);
            Message newMessage = new MimeMessage(sendMailSession);

            // 设置mail主题
            String mail_subject = model.getTitle();
            newMessage.setSubject(mail_subject);

            // 设置发信人地址
            String strFrom = email_user;
            strFrom = new String(strFrom.getBytes(), "iso-8859-1");
            InternetAddress ia = new InternetAddress(strFrom);
            ia.setPersonal("机器人");
            newMessage.setFrom(ia);
            // Address addressFrom[] = { new
            // InternetAddress("617334015@qq.com"),new
            // InternetAddress("goodnight0002@163.com") };
            // 改变发件人地址
            // newMessage.addFrom(addressFrom);
            // 设置收件人地址

            newMessage.setRecipients(Message.RecipientType.TO, model.getAddresss());

            // 设置mail正文
            newMessage.setSentDate(new java.util.Date());
            String mail_text = model.getContent();
            newMessage.setText(mail_text);

            newMessage.saveChanges(); // 保存发送信息
            transport.sendMessage(newMessage, newMessage
                    .getRecipients(Message.RecipientType.TO)); // 发送邮件

            transport.close();
            // Transport.send(newMessage);
            System.out.println("发送成功!");
        } catch (Exception e) {
            System.out.println("发送失败！");
            System.out.println(e);
            e.printStackTrace();
            throw  e;

        }


    }

}
